<link rel="stylesheet" href="../assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/css/bootstrap-table.css">
<link rel="stylesheet" href="../assets/css/sweetalert.css">
<link rel="stylesheet" href="../assets/css/bootstrapValidator.min.css">
<script src="../assets/js/jquery-2.1.4.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/bootstrap-table.js"></script>
<script src="../assets/js/bootstrap-table-export.js"></script>
<script src="../assets/js/bootstrapValidator.min.js"></script>
<script src="http://rawgit.com/hhurz/tableExport.jquery.plugin/master/tableExport.js"></script>
<script src="../assets/js/bootstrap-table-zh-CN.js"></script>
<script src="../assets/js/sweetalert.min.js"></script>
<title>部门信息管理</title>
<style>
    .btn-default {
        height: 34px
    }
</style>
<div class="container" style="width: 90%;height: auto">
    <h1>部门管理</a></h1>
    <form class="form-inline" id="searchForm" style="padding:2px 5px">
        <div class="form-group">
            <label>部门名称:</label>
            <input class="form-control" type="text" id="searchName" name="name">
        </div>
        &#12288;
        <button type="button" class="btn btn-primary" onclick="searchDepartment()"
                style="height: 30px;vertical-align: middle"><i class="glyphicon glyphicon-search"></i> 搜索
        </button>
    </form>
    <hr>
    <div id="toolbar">
        <button id="add" class="btn btn-primary" onclick="add()">
            <i class="glyphicon glyphicon-plus"></i> 添加
        </button>
        <button id="remove" class="btn btn-danger" onclick="removeDepartment()">
            <i class="glyphicon glyphicon-remove"></i> 删除
        </button>
    </div>
    <table id="table" class="table-responsive"
           data-toolbar="#toolbar"
           data-search="false"
           data-show-refresh="true"
           data-show-toggle="true"
           data-show-export="true"
           data-minimum-count-columns="2"
           data-pagination="true"
           data-unique-id="id"
           data-page-number="1"
           data-page-size="10"
           data-page-list="[10, 20, 30, 40]"
           data-pagination-pre-text="上一页"
           data-pagination-next-text="下一页"
           data-show-footer="false"
           data-side-pagination="server"
           data-valign="middle"
           data-url="/department/"
           data-query-params="queryParams"
           data-response-handler="responseHandler">
    </table>
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span
                            aria-hidden="true">&times;</span><span
                            class="sr-only">Close</span></button>
                    <h4 class="modal-title" id="myModalLabel">添加部门</h4>
                </div>
                <div class="modal-body" style="text-align: center">
                    <form class="form-horizontal" id="addForm" role="form">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">部门名称:</label>
                            <div class="col-sm-6">
                                <input class="form-control" type="text" name="name">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary" onclick="saveDepartment()">保存</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span
                            aria-hidden="true">&times;</span><span
                            class="sr-only">Close</span></button>
                    <h4 class="modal-title" id="">编辑部门</h4>
                </div>
                <div class="modal-body" style="text-align: center">
                    <form class="form-horizontal" id="editForm" role="form">
                        <input type="hidden" name="_method" value="put"/>
                        <div class="form-group" hidden>
                            <label class="col-sm-2 control-label">编号:</label>
                            <div class="col-sm-6">
                                <input class="form-control" type="text" id="editId" name="id">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">部门名称:</label>
                            <div class="col-sm-6">
                                <input class="form-control" type="text" id="editName" name="name">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="submit" name="submit" class="btn btn-primary" onclick="updateDepartment()">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        //清除弹窗原数据
        formValidator();
        $("#addModal").on("hidden.bs.modal", function () {
            document.getElementById("addForm").reset();
            $("#addForm").data('bootstrapValidator').destroy();
            $('#addForm').data('bootstrapValidator', null);
            formValidator();
        });
        $("#editModal").on("hidden.bs.modal", function () {
            document.getElementById("editForm").reset();
            $("#editForm").data('bootstrapValidator').destroy();
            $('#editForm').data('bootstrapValidator', null);
            formValidator();
        });
    });
    $("#table").bootstrapTable({
        height: 600,   //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        showColumns: true, //显示隐藏列
        striped: true,
        columns: [
            {
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '编号',
                field: 'id',
                align: 'center',
                valign: 'middle'
            }, {
                title: '部门名称',
                field: 'name',
                align: 'center',
                valign: 'middle'
            },
            {
                title: '操作',
                field: 'operate',
                align: 'center',
                valign: 'middle',
                formatter: operateFormatter
            }
        ]
    });
    function operateFormatter(value, row, index) {
        return [
            '<button id="edit" class="btn btn-success" onclick="edit(' + row.id + ')"><i class="glyphicon glyphicon-edit"></i> 修改</button>'
        ].join('');
    }
    function queryParams(params) {
        return {
            pageSize: params.limit,
            pageNumber: $('#table').bootstrapTable('getOptions').pageNumber,
            sort: params.sortName,
            order: params.sortOrder,
            name: $("#searchName").val()
        };
    }
    function responseHandler(res) {
        return {
            "rows": res.department.list,
            "total": res.department.total
        }
    }
    function searchDepartment() {
        $("#table").bootstrapTable('refresh');
    }
    function add() {
        $("#addModal").modal('show');
    }
    function saveDepartment() {
        //开启验证
        $('#addForm').data('bootstrapValidator').validate();
        if (!$('#addForm').data('bootstrapValidator').isValid()) {
            return;
        }
        $.ajax({
            url: "/department/",
            type: 'POST',
            data: $("#addForm").serialize(),
            async: false,
            success: function (result) {
                if (result.success) {
                    $("#addModal").modal('hide');
                    swal("Good job!", "添加成功", "success");
                    searchDepartment();
                } else {
                    sweetAlert("Oops...", result.message, "error");
                }
            },
            error: function (result) {
                sweetAlert("Oops...", "添加失败", "error");
            }
        });
    }
    function edit(id) {
        var row = $("#table").bootstrapTable("getRowByUniqueId", id);
        $('#editModal').modal('show');
        $("#editId").val(row.id);
        $("#editName").val(row.name);
    }

    function updateDepartment() {
        //开启验证
        $('#editForm').data('bootstrapValidator').validate();
        if (!$('#editForm').data('bootstrapValidator').isValid()) {
            return;
        }
        $.ajax({
            url: "/department/",
            type: 'POST',
            data: $("#editForm").serialize(),
            async: false,
            success: function (result) {
                if (result.success) {
                    $("#editModal").modal('hide');
                    swal("Good job!", "修改成功", "success");
                    searchDepartment();
                } else {
                    sweetAlert("Oops...", result.message, "error");
                }
            },
            error: function (result) {
                sweetAlert("Oops...", "更新失败", "error");
            }
        });
    }
    function removeDepartment() {
        var selections = $("#table").bootstrapTable("getSelections");
        if (selections.length > 0) {
            swal({
                        title: "Are you sure?",
                        text: "是否要删除所选记录!",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "是",
                        cancelButtonText: "否",
                        closeOnConfirm: false
                    },
                    function () {
                        var selections = $("#table").bootstrapTable("getSelections");
                        var strid = "";
                        for (var i = 0; i < selections.length; i++) {
                            strid += selections[i].id + ","
                        }
                        $.ajax({
                            url: "/department/"+strid,
                            type: 'DELETE',
                            async: false,
                            success: function (result) {
                                if (result.success) {
                                    swal("Deleted!", "删除成功.", "success");
                                    searchDepartment();
                                } else {
                                    sweetAlert("Oops...", result.message, "error");
                                }
                            },
                            error: function (result) {
                                sweetAlert("Oops...", "删除失败", "error");
                            }
                        });
                    });
        } else {
            sweetAlert("Oops...", "请选择记录", "error");
        }
    }
    function formValidator() {
        $('#addForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                name: {
                    message: '部门名称验证失败',
                    validators: {
                        notEmpty: {
                            message: '部门名称不能为空'
                        }
                    }
                }
            },
            submitHandler: function (validator, form, submitButton) {
            }
        });
        $('#editForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                name: {
                    message: '部门名称验证失败',
                    validators: {
                        notEmpty: {
                            message: '部门名称不能为空'
                        }
                    }
                }
            },
            submitHandler: function (validator, form, submitButton) {
            }
        });
    }
</script>